﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Messaging;

namespace SilverTraceCallerDemoApp
{
    public partial class MainPage : UserControl
    {
        private LocalMessageSender _sender;

        public MainPage()
        {
            InitializeComponent();
            
            if(Application.Current.InstallState == InstallState.Installed)
            {
                DetouchButton.Visibility = Visibility.Collapsed;
            }
        }

        private void DetouchButton_Click(object sender, RoutedEventArgs e)
        {
            if(Application.Current.InstallState == InstallState.Installed)
            {
                MessageBox.Show("Application is already detached to the desktop.");
                return;
            }
            try
            {
                DetouchButton.Visibility = Visibility.Collapsed;
                Application.Current.Install(); // take the app out of browser
            }
            catch (Exception ex)
            {
                DetouchButton.Visibility = Visibility.Visible;
                MessageBox.Show("Application could not be detached to the desktop." + Environment.NewLine + ex.Message);
            }
        }

        private void SendMessageButton_Click(object source, RoutedEventArgs e)
        {
            var name = SenderNameTxt.Text.Trim();
            var message = SenderMessageTxt.Text.Trim();

            if(name == "")
            {
                MessageBox.Show("Please enter sender name.");
                return;
            }
            if (message == "")
            {
                MessageBox.Show("Please enter message.");
                return;
            }
            if (this._sender != null)
            {
                if (this._sender.ReceiverName != name)
                {
                    this._sender = null;
                }
            }
            if (this._sender == null)
            {
                this._sender = new LocalMessageSender(name);
            }
            this._sender.SendAsync(message);
            SenderMessageTxt.Text = "";
        }


    }
}
